<template>
  <div class="app-container">
    <el-card style="min-height: 800px;">
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item prop="name" label="角色名称：">
          <el-input v-model="listQuery.name" class="input-width" placeholder="请输入角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="listQuery.status" placeholder="请选择用户状态">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查询时间：" prop="beginTime">
          <el-date-picker style="width: 200px" v-model="listQuery.beginTime" align="right" type="date"
            placeholder="选择开始日期" :picker-options="$pickerDateOptions" value-format="yyyy-MM-dd"
            format="yyyy 年 MM 月 dd 日">
          </el-date-picker>
        </el-form-item>
        <el-form-item>-</el-form-item>
        <el-form-item prop="endTime">
          <el-date-picker style="width: 200px" v-model="listQuery.endTime" align="right" type="date"
            placeholder="选择结束日期" :picker-options="$pickerDateOptions" value-format="yyyy-MM-dd"
            format="yyyy 年 MM 月 dd 日">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" style=" margin-right: 15px" @click="handleResetSearch()"
            size="small">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="handleSearchList()" size="small">查询</el-button>
        </el-form-item>
      </el-form>
      <el-button v-btnpermission="$btnPer.roleBtnRules.addRole" size="mini" class="btn-add" type="primary"
        icon="el-icon-plus" @click="handleAdd()">添加角色</el-button>
      <el-button size="small" v-btnpermission="$btnPer.roleBtnRules.batchDelete" type="primary"
        @click="deleteAdminList"><i class="el-icon-delete"></i> 批量删除</el-button>
      <div></div>

      <div class="table-container">
        <el-table ref="roleTable" :data="list" style="width: 100%" v-loading="listLoading"
          @selection-change="selectTableList" border>
          <el-table-column type="selection" :selectable="selecTableItem" width="40"></el-table-column>
          <el-table-column label="编号" width="100" align="center" type="index"></el-table-column>
          <el-table-column label="角色名称" align="center" prop="name"></el-table-column>
          <el-table-column label="描述" align="center" prop="description"></el-table-column>
          <el-table-column label="用户数" width="100" align="center" prop="adminCount"></el-table-column>
          <el-table-column label="状态" width="140" align="center">
            <template slot-scope="scope">
              <el-switch v-btnpermission="$btnPer.roleBtnRules.editRoleStatus"
                @change="handleStatusChange(scope.$index, scope.row)" :active-value="1" :inactive-value="0"
                v-model="scope.row.status"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="160" align="center" prop="createTime"></el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template slot-scope="scope">
              <el-row>
                <!-- <el-button
                size="mini"
                type="text"
                @click="handleSelectMenu(scope.$index, scope.row)"
                >分配菜单
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleSelectResource(scope.$index, scope.row)"
                >分配资源
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleSelectData(scope.$index, scope.row)"
                :disabled="scope.row.name == '超级管理员'"
                >数据权限
              </el-button> -->
              </el-row>
              <el-row>
                <el-button size="mini" type="text" v-if="scope.row.id !== 1"
                  v-btnpermission="$btnPer.roleBtnRules.editRole" @click="handleUpdate(scope.$index, scope.row)">
                  编辑
                </el-button>
                <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)"
                  v-btnpermission="$btnPer.roleBtnRules.deleteRole" v-if="scope.row.id !== 1">删除
                </el-button>
                <el-dropdown @command="handleCommand($event, scope.row)" v-if="scope.row.id !== 1">
                  <span class="el-dropdown-link" :class="name !== 'admin' && scope.row.id == 1
                    ? 'desablebtn'
                    : 'defaultbtn'
                    ">
                    更多
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-btnpermission="$btnPer.roleBtnRules.relationMenu" command="menu"
                      :disabled="name !== 'admin' && scope.row.id == 1">分配菜单</el-dropdown-item>
                    <el-dropdown-item v-btnpermission="$btnPer.roleBtnRules.relationResource" command="info"
                      :disabled="name !== 'admin' && scope.row.id == 1">分配资源</el-dropdown-item>
                    <el-dropdown-item v-btnpermission="$btnPer.roleBtnRules.relationData" command="data"
                      :disabled="name !== 'admin' && scope.row.id == 1">数据权限</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper" :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize" :page-sizes="[10, 15, 20]" :total="total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog :title="isEdit ? '编辑角色' : '添加角色'" :visible.sync="dialogVisible" center width="500px">
      <el-form :model="role" :rules="addUserRules" ref="roleForm" label-width="150px" size="small">
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="role.name" placeholder="请输入角色名称" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio-group v-model="role.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述：">
          <el-input v-model="role.description" placeholder="请输入内容" type="textarea" :rows="5"
            style="width: 250px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
        <el-button @click="cancleAddRole" size="small">取 消</el-button>
      </span>
    </el-dialog>
    <editRole ref="editRoleRef"></editRole>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import {
  fetchList,
  createRole,
  updateRole,
  updateStatus,
  deleteRole
} from "@/api/role";
import { formatDate } from "@/utils/date";
import editRole from "./components/editRole.vue";
import { color } from "echarts/lib/theme/light";
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  name: null,
  beginTime: "",
  endTime: ""
};
const defaultRole = {
  id: null,
  name: null,
  description: null,
  adminCount: 0,
  status: 1
};
export default {
  name: "roleList",
  components: {
    editRole
  },
  computed: {
    ...mapGetters(["sidebar", "avatar", "name", "bgColor"])
  },
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      dataTime: [],
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      role: Object.assign({}, defaultRole),
      addUserRules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
      },
      isEdit: false,
      deleteList: [],
      // 搜索条件状态下拉数据
      options: [
        { value: "1", label: "启用" },
        { value: "0", label: "停用" }
      ]
    };
  },
  created() {
    this.getList();
  },
  filters: {
    formatDateTime(time) {
      if (time == null || time === "") {
        return "N/A";
      }
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  methods: {
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.$authDate(this.listQuery.beginTime, this.listQuery.endTime, v => {
        if (!v.type) {
          return this.$message.warning(v.msg);
        } else {
          // console.log(this.searchForm);
          this.getList();
        }
      });
    },
    selecTableItem(row) {
      if (row.id !== 1) {
        return true;
      }
    },
    handleCommand(v, row) {
      // console.log(v, row);
      if (v == "menu") {
        this.handleSelectMenu(row);
      } else if (v == "info") {
        this.handleSelectResource(row);
      } else if (v == "data") {
        this.handleSelectData(row);
      }
    },
    handleSelectData(row) {
      this.$refs.editRoleRef.openLog(row);
    },
    // 批量删除角色
    deleteAdminList() {
      if (this.deleteList.length > 0) {
        let ids = this.deleteList;
        this.$confirm("是否确认批量删除选择的用户？", "提示", {
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
          .then(async () => {
            let params = new URLSearchParams();
            params.append("ids", ids);
            deleteRole(params).then(() => {
              this.$message.success("删除成功！");
              this.getList();
            });
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      } else {
        this.$message.error("请选择要删除的数据");
      }
    },
    handleResetSearch() {
      this.dataTime = [];
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.role = Object.assign({}, defaultRole);
    },
    selectTableList(val) {
      this.deleteList = val.map(v => v.id);
    },
    handleStatusChange(index, row) {
      this.$confirm("是否要修改该状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateStatus(row.id, { status: row.status }).then(response => {
            this.$message({
              type: "success",
              message: "修改成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消修改"
          });
          this.getList();
        });
    },
    handleDelete(index, row) {
      this.$confirm("是否要删除该角色?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let ids = [];
        ids.push(row.id);
        let params = new URLSearchParams();
        params.append("ids", ids);
        deleteRole(params).then(response => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getList();
        });
      });
    },
    handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      this.role = Object.assign({}, row);
    },
    cancleAddRole() {
      this.dialogVisible = false;
      this.$refs.roleForm.resetFields();
    },
    handleDialogConfirm() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.$confirm("是否确认添加?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            if (this.isEdit) {
              updateRole(this.role.id, this.role).then(response => {
                this.$message({
                  message: "修改成功！",
                  type: "success"
                });
                this.dialogVisible = false;
                this.getList();
              });
            } else {
              createRole(this.role).then(response => {
                this.$message({
                  message: "添加成功！",
                  type: "success"
                });
                this.dialogVisible = false;
                this.getList();
              });
            }
          });
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    handleSelectMenu(row) {
      this.$router.push({
        path: "/ums/allocMenu",
        query: { roleId: row.id, name: row.name }
      });
    },
    handleSelectResource(row) {
      this.$router.push({
        path: "/ums/allocResource",
        query: { roleId: row.id }
      });
    },
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
      });
    }
  }
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 50px);
  background-color: #f5f5f5;
  padding: 20px;
}

.desablebtn {
  color: #c0c4cc;
  cursor: not-allowed !important;
}

.defaultbtn {
  color: #409eff;
}

.el-dropdown-link {
  cursor: pointer;
  font-size: 12px;
  margin-left: 10px;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>
